"use strict";

import axios from "axios";
import {Message, Loading} from "element-ui";
import {getToken} from "@/utils/auth";
import qs from 'qs-stringify';
// Full config:  https://github.com/axios/axios#request-config
axios.defaults.headers.post["Content-Type"] =
    "application/json;charset=UTF-8";
let msgTimeout = 3000;
let config = {
    baseURL: process.env.NODE_ENV === 'production' ? process.env.VUE_APP_apiUrl : '/',
    timeout: 2000 * 1000, // Timeout
    withCredentials: true // Check cross-site Access-Control
};
let extra = {};

// const CancelToken = axios.CancelToken
// const source = CancelToken.source()
// create an axios instance
const service = axios.create(config);
var loading;
// request interceptor
service.interceptors.request.use(
    config => {
        let param = config.data || config.params;
        if (param && "noloading" in param) {
            delete param.noloading;
            param = null;
        } else {
            loading = Loading.service({
                fullscreen: true,
                body: true,
                lock: true,
                background: "rgba(0, 0, 0, 0.5)",
                text: "正在操作，请稍后..."
            });
        }
        // if (sessionStorage.getItem('isLogin') != '1') {
        //     config.cancelToken = source.token
        //     // 取消请求（message 参数是可选的）
        //     source.cancel('Operation canceled by the user.')
        // }
        if (config.method === "post") {
            config.data = {...extra, ...config.data};
            // config.data = qs(config.data);
        } else {
            config.params = {...extra, ...config.params};
        }
        if (param && "BLOB" in param) {
            config.headers["Content-Type"] = 'application/vnd.ms-excel;charset=utf-8'
            config['responseType'] = 'blob'
        }
        if (getToken()) {
            config.headers["token"] = getToken();
        }
        return config;
    },
    error => {
        Message.error(error, msgTimeout);
        loading.close();
        return Promise.reject(error);
    }
);
// response interceptor
service.interceptors.response.use(
    response => {
        if(response.headers['content-disposition']) {
            loading.close();
            return {data: response.data, resultInfo: '文件下载成功！', fileName: response.headers['content-disposition'].split(';')}
        } else if(response.data.resultCode === '200009'){
            loading.close()
            Message.error(response.data.resultInfo, msgTimeout);
            setTimeout(()=>{;
                if(process.env.NODE_ENV !== "development") {
                    sessionStorage.setItem('isLogin', '0')
                    window.location.href = '#/login'
                }
            },1500)
            return response;
        } else {
            const res = response.data;
            loading.close();
            return res;
        }
    },
    error => {
        loading.close();
        Message.error('系统异常', msgTimeout);
        return Promise.reject(error);
    }
);

export default {
    http: service,
    install(Vue) {
        Vue.axios = service;
        window.axios = service;
        Object.defineProperties(Vue.prototype, {
            axios: {
                get() {
                    return service;
                }
            },
            $axios: {
                get() {
                    return service;
                }
            }
        });
    }
};
